package message.rabbitmq.direct;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import message.rabbitmq.RabbitMQUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * direct
 * 消息会被消费者分食
 */
public class DirectProducer {

    public static final String QUEUE_NAME = "direct_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        RabbitMQUtil.checkServer();

        //创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置host
        connectionFactory.setHost("localhost");
        //创建连接
        Connection connection = connectionFactory.newConnection();
        //创建频道
        Channel channel = connection.createChannel();
        //设置消息类型
        channel.exchangeDeclare(QUEUE_NAME, BuiltinExchangeType.TOPIC);

        //发送消息
        for (int i = 0; i < 50; i++) {
            String message = "direct消息:" + i;
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8));
            System.out.println("DirectProducer发送消息:" + i);
        }

        //关闭连接
        channel.close();
        connection.close();
    }
}
